/**
 * @filename:SaleOrderController Feb 18, 2025
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2020 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.SysAdminService;
import com.wonder.app.domain.SaleOrder;
import com.wonder.app.service.SaleOrderService;
import com.wonder.app.request.SaleOrderRequest;
import com.wonder.framework.authorization.CheckAdminToken;
import io.swagger.annotations.ApiParam;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * <p>说明： 销售订单API接口层</P>
 * @version: 1.1.0
 * @author: Wonder
 * @time    Feb 18, 2025
 *
 */
@Api(tags = "销售订单")
@RestController
@RequestMapping("/app/SaleOrder")
public class SaleOrderController {

	@Autowired
	private CheckAdminToken checkAdminToken;

	@Autowired
	private SysAdminService adminService;

	@Autowired
	private RedissonClient redissonClient;
	
	@Autowired
	private SaleOrderService saleOrderService;
	
	@ApiOperation(value = "销售订单列表")
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public Map<String,Object> index(@RequestBody SaleOrderRequest saleOrderRequest) {
		Page<SaleOrder> page = new Page<SaleOrder>(saleOrderRequest.getPage(), saleOrderRequest.getLimit());
		IPage<SaleOrder> list = saleOrderService.selectList(saleOrderRequest, page);
		
		Map<String,Object> retMap=new HashMap<>();
		retMap.put("data",CommonPage.restPage(list));
		
  
		return AjaxMap.success(retMap);
	}
	
	/**
	 * @explain 修改排序开关
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/updateExt")
	@ApiOperation(value = "修改排序开关", notes = "作者：Wonder")
	public AjaxResult<SaleOrder> updateExt(@RequestBody SaleOrder entity){
		if (null!=entity) {
			boolean rsg = saleOrderService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success("system.updateSuccess");
			  }else {
				  return AjaxResult.failed("system.updateFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	
	/**
	 * @explain 添加
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/add")
	@ApiOperation(value = "添加", notes = "作者：Wonder")
	public AjaxResult<SaleOrder> add(@RequestBody SaleOrder entity){

		if (null!=entity) {
		    
		    String validate=saleOrderService.validate(entity,"new");
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);    
			boolean rsg = saleOrderService.save(entity);
			if (rsg) {
				  return AjaxResult.success("system.insertSuccess");
			  }else {
				  return AjaxResult.failed("system.insertFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	
	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/getUpdateInfo")
	@ApiOperation(value = "获取销售订单对象", notes = "作者：Wonder")
	public AjaxResult<SaleOrder> getUpdateInfo(@RequestBody Map<String,Object> map){
	    if(map==null) return AjaxResult.failed("system.parameterError");
		Long Id=Long.parseLong(map.get("Id").toString());		
		 SaleOrder saleOrder=saleOrderService.getById(Id);
		
		if (null!=saleOrder ) {
			 return AjaxResult.success(saleOrder);
		}else {
			 return AjaxResult.failed("system.parameterError");
		}
		
	}
	
	/**
	 * @explain 修改
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "作者：Wonder")
	public AjaxResult<SaleOrder> update(@RequestBody SaleOrder entity){
		if (null!=entity) {
		    String validate=saleOrderService.validate(entity,"update");
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);
			boolean rsg = saleOrderService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success("system.updateSuccess");
			  }else {
				  return AjaxResult.failed("system.updateFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	/**
	 * @explain 查看对象明细
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@ApiOperation(value = "查询saleorder明细")
	@ResponseBody
	@PostMapping(value = "/saleorderdelete")

	public AjaxResult<Map<String,Object>> getSaleOrderDelete(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{

		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		String userName = user.getName();
		Long user_id = user.getUser_id();
		Map<String,Object> data = saleOrderService.getSaleOrderDelete(map,user_id);
		if (null != data){
			return AjaxResult.success(data);
		} else {
			return AjaxResult.failed();
		}
	}
	/**
	 * @explain 删除
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "删除", notes = "作者：Wonder")
	public AjaxResult<SaleOrder> delete(@RequestBody Map<String,Object> map){
		if(map==null)return AjaxResult.failed("system.parameterError");
		String ids=map.get("Id").toString();
		ids=StringUtils.remove(ids, '[');
		ids=StringUtils.remove(ids, ']');
		String[] deleteIds=StringUtils.split(ids, ',');
		List<Long> idList=new ArrayList<>(); 
		for(int i=0;i<deleteIds.length;i++)
		{
			idList.add( Long.parseLong(deleteIds[i].trim()));//整数数组
		}

	    boolean rsg = saleOrderService.removeBatchByIds(idList);
	    if (rsg) {
		    return AjaxResult.success("system.deleteSuccess");
	    }else {
		   return AjaxResult.failed("system.deleteFailed");
	    }
		
	}
	
	/**
	 * @explain 查看对象明细  
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@ApiOperation(value = "查询saleorder明细")
	@ResponseBody
	@PostMapping(value = "/saleorderdetail")

	public AjaxResult<Map<String,Object>> getSaleOrderDetail(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
		if (null == map){
			return AjaxResult.failed("system.parameterError");
		}
		Map<String,Object> data = saleOrderService.getSaleOrderDetail(map);
		if (null != data){
			return AjaxResult.success(data);
		} else {
			return AjaxResult.failed();
		}
	}
	
	/**
	 * @explain 导入
	 * @param   map 对象参数：List<Map>
	 * @return  Map<String,Object>
	 * @author  Wonder
	 */

    @PostMapping("/importData")
    @ApiOperation(value = "导入", notes = "作者：Wonder")
    public AjaxResult<Object> importData(HttpServletRequest request,@RequestBody List<Map<String, Object>> map ) throws Exception {

		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		String userName = user.getName();
		Long user_id = user.getUser_id();

		//每个用户一个独立的锁
		String lockKey = "lock:user:" + user_id + ":dowork";
		RLock lock = redissonClient.getLock(lockKey);
		boolean locked = false;
		try {
			locked = lock.tryLock(0,-1, TimeUnit.SECONDS);
			if (!locked){
				throw new RuntimeException("请求处理中，请勿重复请求");
			}
			return saleOrderService.importData(userName,user_id,map);
		} catch (Exception e){
			return AjaxResult.failed(e.getMessage());
		} finally {
			// 解锁必须确保是当前线程持有锁
			if (locked && lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}


    }

	/**
	 * @explain 导入销售订单变更单
	 * @param   map 对象参数：List<Map>
	 * @return  Map<String,Object>
	 * @author  Wonder
	 */

	@PostMapping("/import_update_data")
	@ApiOperation(value = "导入", notes = "作者：Wonder")
	public AjaxResult<Object> importUpdateData(@RequestBody List<Map<String, Object>> map ) throws Exception {
		return saleOrderService.importUpdateData(map);
	}

	@PostMapping("/get_stock")
	@ApiOperation(value = "获取仓库信息", notes = "作者：Wonder")
	public Map<String,Object> getStock(@RequestBody Map<String, Object> map ) throws Exception {
		String billNo = map.get("billNo").toString();
		return saleOrderService.getStok(billNo);
	}

}